var active = false;

function editaProfile() {
	
	run_waitMe();
	
	limparMensagem();
	desabilitaBotoes();
	
	$.ajax({
        url:  basepath+"admin/profile/editarProfile",
        data: $('#formProfile').serialize(),
        type: 'POST',
        async: false,
        success: function(retorno){
        	
        	stop_waitMe();
        	
    		if (retorno == true) {
    			
    			var obj = new Object();

			    obj.toastr = "success";
			    obj.title = "Profile";
			    obj.msg = "Alterado com sucesso!";

			    var mensagem = JSON.stringify(obj);  
			    
    			// Creating cookie
    			$.cookie('toastr', mensagem, { path: '/' }); 
                
                window.parent.location = basepath+"admin";

    		} else {
    			
    			habilitaBotoes();
    			
    			//Rola a página para cima
    			$('html, body').animate({ scrollTop: 0 }, 'slow');
    			
    			// Mostra mensagem
    			$("#mensagem").show();
    			$("#mensagem").prepend('<div class="row alert '+obj.tipoMensagem+' alert-dismissible" role="alert"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>'+obj.mensagem+'</div>');
    		}
        	
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
        	stop_waitMe();
        	
        	habilitaBotoes();
        	
        	//Rola a página para cima
    		$('html, body').animate({ scrollTop: 0 }, 'slow');
        	
    		// Mostra mensagem
			$("#mensagem").show();
			$("#mensagem").prepend('<div class="row alert alert-danger alert-dismissible" role="alert"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>Ocorreu um erro. Tente novamente mais tarde!</div>');
        }
    });

}

function limpaCampo(){
	$('#formProfile').each (function(){
	  this.reset();
	});
}

function desabilitaBotoes(){
	// Desabilita os botões
	$("#buttonSalvar").attr("disabled", "disabled");
	$("#buttonVoltar").attr("disabled", "disabled");
	
	$("#buttonCancelarModal").attr("disabled", "disabled");
	$("#buttonSalvarModal").attr("disabled", "disabled");
}

function habilitaBotoes(){
	// Habilita o botão novamente
	$("#buttonSalvar").removeAttr("disabled");
	$("#buttonVoltar").removeAttr("disabled");
	
	$("#buttonCancelarModal").removeAttr("disabled");
	$("#buttonSalvarModal").removeAttr("disabled");
}

function limparMensagem(){
	// Limpando dados da mensagem
	$("#mensagem").hide();
	$("#mensagem").html("");
}

function limparMensagemModal(){
	// Limpando dados da mensagem
	$("#mensagemModal").hide();
	$("#mensagemModal").html("");
}

function limparForm(){
	$('#formProfile').data('formValidation').resetForm();
}

function formProfile() {
	
	$('#formProfile').formValidation({
		framework: 'bootstrap',
        icon: {
            valid: 'glyphicon glyphicon-ok',
            invalid: 'glyphicon glyphicon-remove',
            validating: 'glyphicon glyphicon-refresh'
        },
        button: {
		    // The disabled class
		    disabled: ''
		},
        fields : {
			nome : {
				validators : {
					notEmpty : {
						message : 'Nome deve ser informado.'
					}
				}
			},
			cpf: {
				verbose: false,
                validators: {
                	notEmpty : {
						message : 'CPF deve ser informado.'
					},
                    id: {
                        country: 'BR',
                        message: 'CPF inválido'
                    },
                    remote: {
                    	message : 'CPF já cadastrado! Por favor informe outro.',
                    	url: basepath+"admin/profile/validaCpfDisponivel",
                     	data: {
                            cpf: 'cpf'
                     	},
                     	type: 'POST'
                    }
                }
            },
			email : {
				verbose: false,
				validators : {
					notEmpty : {
						message : 'Email deve ser informado.'
					},
					emailAddress: {
						message: 'Email inválido.'
					},
					remote: {
	                	message : 'Email já cadastrado! Por favor informe outro.',
	                	url: basepath+"admin/profile/validaEmailDisponivel",
	                 	data: {
	                        email: 'email'
	                 	},
	                 	type: 'POST'
	                }
				}
			},
			login : {
				verbose: false,
				validators : {
					notEmpty : {
						message : 'Login deve ser informado.'
					},
					stringLength: {
	                    min: 3,
	                    message: 'Login deve conter no minímo 3 caracteres.'
	                },
	                regexp: {
	                    regexp: /^[a-zA-Z0-9_\.]+$/,
	                    message: 'Caracter especial inválido.'
	                },
	                remote: {
	                	message : 'Login já cadastrado! Por favor informe outro.',
	                	url: basepath+"admin/profile/validaLoginDisponivel",
	                 	data: {
	                        login: 'login'
	                 	},
	                 	type: 'POST'
	                }
				}
			}
		}
	})	
	.on('success.form.fv', function(e) {
		// Prevent form submission		
        e.preventDefault();
        
		editaProfile();
    });
}

function inicializandoComponentes(){
	
	(function(factory) {
		if (typeof define === 'function' && define.amd) {
		define([ 'jquery' ], factory);
	} else if (typeof exports === 'object') {
		// Node / CommonJS
		factory(require('jquery'));
	} else {
		factory(jQuery);
	}})
	
	(function($) {
	
		'use strict';
	
		var console = window.console || {
			log : function() {
			}
		};
	
		function CropAvatar() {
			
			this.$container = $('.ibox-content');
			this.$containerModal = $('#avatar-modal');
	
			this.$avatarView = this.$container.find('div.avatar-view');
			this.$avatar = this.$avatarView.find('img');
			
			this.$avatarModal = this.$containerModal;
			this.$avatarForm = this.$avatarModal.find('.avatar-form');
			this.$avatarSrc = this.$avatarForm.find('.avatar-src');
			this.$avatarData = this.$avatarForm.find('.avatar-data');
			this.$avatarInput = this.$avatarForm.find('.avatar-input');
			this.$avatarSave = this.$avatarForm.find('.avatar-save');
			this.$avatarBtns = this.$avatarForm.find('.avatar-btns');
	
			this.$avatarWrapper = this.$avatarModal.find('.avatar-wrapper');
			this.$avatarPreview = this.$avatarModal.find('.avatar-preview');
	
			this.init();
		}
	
		CropAvatar.prototype = {
			constructor : CropAvatar,
	
			support : {
				fileList : !!$('<input type="file">').prop('files'),
				blobURLs : !!window.URL && URL.createObjectURL,
				formData : !!window.FormData
			},
	
			init : function() {
				this.support.datauri = this.support.fileList
						&& this.support.blobURLs;
	
				if (!this.support.formData) {
					this.initIframe();
				}
	
				this.initTooltip();
				this.initModal();
				this.addListener();
			},
	
			addListener : function() {
				this.$avatarView.on('click', $.proxy(this.click, this));
				this.$avatarInput.on('change', $.proxy(this.change, this));
				this.$avatarForm.on('submit', $.proxy(this.submit, this));
				this.$avatarBtns.on('click', $.proxy(this.zoom, this));
			},
	
			initTooltip : function() {
				this.$avatarView.tooltip({
					placement : 'bottom'
				});
			},
	
			initModal : function() {
				this.$avatarModal.modal({
					show : false
				});
			},
	
			initPreview : function() {
				var url = this.$avatar.attr('src');
	
				this.$avatarPreview.empty().html('<img src="' + url + '">');
			},
	
			initIframe : function() {
				var target = 'upload-iframe-' + (new Date()).getTime(), $iframe = $(
						'<iframe>').attr({
					name : target,
					src : ''
				}), _this = this;
	
				// Ready ifrmae
				$iframe.one('load', function() {
	
					// respond response
					$iframe.on('load', function() {
						var data;
	
						try {
							data = $(this).contents().find('body').text();
						} catch (e) {
							console.log(e.message);
						}
	
						if (data) {
							try {
								data = $.parseJSON(data);
							} catch (e) {
								console.log(e.message);
							}
	
							_this.submitDone(data);
						} else {
							_this.submitFail('Image upload failed!');
						}
	
						_this.submitEnd();
	
					});
				});
	
				this.$iframe = $iframe;
				this.$avatarForm.attr('target', target).after(
						$iframe.hide());
			},
	
			click : function() {
				$("#buttonSalvarModal").attr("disabled", "disabled");
				
				this.$avatarModal.modal('show');
				this.initPreview();
			},
	
			change : function() {
				var files, file;
	
				if (this.support.datauri) {
					files = this.$avatarInput.prop('files');
	
					if (files.length > 0) {
						file = files[0];
	
						if (this.isImageFile(file)) {
							
							limparMensagemModal()
							
							$("#buttonSalvarModal").removeAttr("disabled");
							
							if (this.url) {
								URL.revokeObjectURL(this.url); // Revoke the old one
							}
	
							this.url = URL.createObjectURL(file);
							this.startCropper();
						}else{
							$("#buttonSalvarModal").attr("disabled", "disabled");
						}
					}else{
						$("#buttonSalvarModal").attr("disabled", "disabled");
					}
				} else {
					file = this.$avatarInput.val();
	
					if (this.isImageFile(file)) {
						this.syncUpload();
					}
				}
			},
	
			submit : function(e) {
				
				if (!this.$avatarSrc.val() && !this.$avatarInput.val()) {
					return false;
				}
				
				var files, file;
				
				files = this.$avatarInput.prop('files');
				
				if (files.length > 0) {
					file = files[0];

					if (this.isImageFile(file)) {
						
						if (this.support.formData) {
							this.ajaxUpload();
							return false;
						}
						
					}else{
						return false;
					}
				}else{
					return false;
				}
				
			},
	
			zoom : function(e) {
				var data;
	
				if (active) {
					data = $(e.target).data();
					
					if (data.method) {
						this.$img.cropper(data.method, data.option);
					}
				}
			},
	
			isImageFile : function(file) {
				if (file.type) {
					return /^image\/\w+$/.test(file.type);
				} else {
					return /\.(jpg|jpeg|png|gif)$/.test(file);
				}
			},
	
			startCropper : function() {
				var _this = this;
	
				if (active) {
					this.$img.cropper('replace', this.url);
				} else {
					this.$img = $('<img src="' + this.url + '">');
					this.$avatarWrapper.empty().html(this.$img);
					
					this.$img.cropper({
						aspectRatio : 1,
						preview : this.$avatarPreview.selector,
						dragCrop: false,
						resizable: true,
						crop : function(data) {
							var json = [ '{"x":' + data.x, '"y":' + data.y,
									'"height":' + data.height,
									'"width":' + data.width,
									'"rotate":' + data.rotate + '}' ]
									.join();
	
							_this.$avatarData.val(json);
							
							$('#dataHeight').val(Math.round(data.height));
							$('#dataWidth').val(Math.round(data.width));
						}
					});
	
					active = true;
				}
			},
	
			stopCropper : function() {
				if (active) {
					this.$img.cropper('destroy');
					this.$img.remove();
					active = false;
				}
			},
	
			ajaxUpload : function() {
				var url = this.$avatarForm.attr('action'), data = new FormData(
						this.$avatarForm[0]), _this = this;
	
				$.ajax(url, {
					type : 'post',
					data : data,
					dataType : 'json',
					processData : false,
					contentType : false,
	
					beforeSend : function() {
						_this.submitStart();
					},
	
					success : function(data) {
						_this.submitDone(data);
					},
	
					error : function(XMLHttpRequest, textStatus,
							errorThrown) {
						_this.submitFail(textStatus || errorThrown);
					},
	
					complete : function() {
						_this.submitEnd();
					}
				});
			},
	
			syncUpload : function() {
				this.$avatarSave.click();
			},
	
			submitStart : function() {
				run_waitMe();
				limparMensagemModal();
				desabilitaBotoes();
			},
	
			submitDone : function(data) {
				stop_waitMe();
				habilitaBotoes();
				
				var obj = jQuery.parseJSON( JSON.stringify(data) );	
				
				if (!jQuery.isEmptyObject({obj})){
					
					if (obj.sucesso){
						
						this.url = obj.src;
						this.cropDone();
						
						toastr.options = {
							"closeButton": true,
							"debug": false,
							"progressBar": true,
							"positionClass": "toast-top-right",
							"onclick": null,
							"showDuration": "400",
							"hideDuration": "1000",
							"timeOut": "7000",
							"extendedTimeOut": "1000",
							"showEasing": "swing",
							"hideEasing": "linear",
							"showMethod": "fadeIn",
							"hideMethod": "fadeOut"
				        };
								
						// Display a success toast, with a title
		                toastr.success(obj.msg,'Imagem');
						
					}else{
						this.alert(obj.msg, obj.tipoMensagem);
					}
					
				}else {
					this.alert('Ocorreu um erro. Tente novamente mais tarde!', 'alert-danger');
				}
			},
	
			submitFail : function(msg) {
				stop_waitMe();
				habilitaBotoes();
				
				this.alert("Submit Fail", 'alert-danger');
			},
	
			submitEnd : function() {
				stop_waitMe();
				habilitaBotoes();
				
			},
	
			cropDone : function() {
				this.$avatarForm.get(0).reset();
				
				//Foto Profile
				this.$avatar.attr('src', this.url);
				
				//Foto do Admin
				$("#fotoAdmin").attr('src', this.url);
				this.stopCropper();
				this.$avatarModal.modal('hide');
			},
	
			alert : function(msg, tipoMensagem) {
				 // Mostra mensagem
     			$("#mensagemModal").show();
     			$("#mensagemModal").prepend('<div class="alert '+tipoMensagem+' alert-dismissible" role="alert"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>'+msg+'</div>');
	
			}
		};
	
		$(function() {
			return new CropAvatar();
		});
	
	});
	
	 var $inputImage = $("#avatarInput");
	 var $image = $('.avatar-wrapper > img');
	 
     if (window.FileReader) {
         $inputImage.change(function() {
             var fileReader = new FileReader(),
                     files = this.files,
                     file;

             if (!files.length) {
                 return;
             }

             file = files[0];

             if (/^image\/\w+$/.test(file.type)) {
                 fileReader.readAsDataURL(file);
             } else {
            	 // Mostra mensagem
     			$("#mensagemModal").show();
     			$("#mensagemModal").prepend('<div class="alert alert-danger alert-dismissible" role="alert"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>Por favor escolha um arquivo do tipo imagem!</div>');
             }
         });
     } else {
         $inputImage.addClass("hide");
     }
     
    $('#avatar-modal').on('hidden.bs.modal', function (e) {
    	 $('.avatar-form').each (function(){
    		  this.reset();
    	 });
    	 
    	 $image.cropper('reset');
    	 $image.cropper('destroy');
    	 
    	 $(".avatar-wrapper").html("");
    	 
		 active = false;
	})
	
	var today = dataAtual();
	
	$('#data-calendario .input-group.date').datepicker({
		endDate: today, 
        startView: 2,
        todayBtn: "linked",
        keyboardNavigation: false,
        forceParse: false,
        todayHighlight: true,
        autoclose: true
    });
	
	$("#buttonVoltar").bind('click',function(e) {
		// Prevent form submission
        e.preventDefault();
        
        window.parent.location = basepath+"admin";
	});	
	
	 var SPMaskBehavior = function (val) {
		 return val.replace(/\D/g, '').length === 11 ? '(00) 00000-0000' : '(00) 0000-00009';
	 },
	 spOptions = {
		onKeyPress: function(val, e, field, options) {
			field.mask(SPMaskBehavior.apply({}, arguments), options);
	    }
	 };

	 $('#telefone').mask(SPMaskBehavior, spOptions);
	 $('#celular').mask(SPMaskBehavior, spOptions);
	 $('#cpf').mask('999.999.999-99');
}

function init() {
	
	inicializandoComponentes();
	
	formProfile();
}

$(document).ready(init);